import { defineConfig } from 'vite'
import { mkdir, writeFile } from 'node:fs/promises'
import { join, resolve } from 'node:path'

const files = ['douyin']

const buildEntry = files.reduce((entry, file) => {
  entry[file] = join(__dirname, file, 'index.ts')
  return entry
}, {} as Record<string, string>)

export default defineConfig(() => {
  return {
    root: './',
    server: {
      port: 3000,
    },
    build: {
      minify: false,
      outDir: resolve(__dirname, '../core/public/user-scripts'),
      lib: {
        name: 'userScripts',
        formats: ['es'],
        entry: buildEntry,
      },
    },
    plugins: [
      {
        name: 'vite-plugin-write-content-server',
        enforce: 'post',
        configureServer({ httpServer, config }) {
          if (config.command === 'serve')
            httpServer?.once('listening', () => {
              const address = httpServer.address()
              if (typeof address === 'object' && address?.port) {
                const { outDir } = config.build
                mkdir(outDir, { recursive: true }).finally(() => {
                  files.forEach(file => {
                    const output = join(outDir, `${file}.js`)
                    const content = `import('http://localhost:${address.port}/@vite/client');import('http://localhost:${address.port}/${file}/index.ts');`
                    writeFile(output, content, { flag: 'w+' })
                  })
                })
              }
            })
        },
      },
    ],
  }
})
